<template>
  <div>
    <myheader></myheader>
    <section class="featured-block text-center">
      <div class="container">
        <div>
          <Breadcrumb :datas="datas"></Breadcrumb>
        </div>
      </div>
    </section>

    <table>
      <tr>
        <td>
          <Avatar :src="src" wifth="150" fit="fill"></Avatar>
        </td>
        <td>
					<Button color="red" @click="del_Avatar">删除</Button>
					&emsp;&emsp;
					<input type="text" v-model="dirname"/><Button color="blue" @click="newdir">创建目录</Button>
        </td>
        
      </tr>
      <tr>
        <td>用户头像：</td>
        <td>
          <input type="file" @change="upload"/>
        </td>
      </tr>
      <tr>
        <td>手机号：</td>
        <td>
          <input type="text" :placeholder="phone" v-model="phone"/>
          <Button @click="update_phone">更改</Button>
          <span style="color:red">{{phonemsg}}</span>
        </td>
      </tr>
      <tr>	
        <td>
          七牛云上传:
        </td>
        <td>
          <input type="file" @change="upload_qiniu"/>
          {{load_percent}}
          <br>
          <!-- 进度条标签 -->
          <Progress v-show="load_int" color='red' :percent='load_int'>
            <span>{{load_int}}%</span>
          </Progress>
        </td>
    </tr>
    <tr>	
        <td>
          又拍云上传:
        </td>
        <td>
          <div class="upload">拖拽上传:<input type="file" @change="upload_upyun"/></div>
        </td>
    </tr>
      <tr>
        <td>视频：</td>
        <td>
          <video id='video' v-show="videosrc" width="300" height="200" :src="videosrc" controls='contros' autoplay='autoplay' muted loop='loop'></video>
        </td>
        <td><Button color='blue' @click="into" v-show="videosrc">画中画模式</Button></td>
      </tr>
    </table>
    <footer class="footer">
      <div class="container">@v3u.cn</div>
    </footer>
  </div>
</template>

<script>
import axios from "axios";
import myheader from "./myheader.vue";
// 导入文件
import {config} from '../config.js'
export default {
  data() {
    return {
      phone:'',
      phonemsg:'',
      //整形进度
      load_int:0,
      //进度条
      load_percent:'',
      //文件夹名称
      dirname:'',
      src: "",
      //视频地址
      videosrc:'',
      msg: "这是一个变量",
      //七牛云token
      token:'',
      //面包屑导航变量
      datas: [
        { title: "首页", route: { name: "index" } },
        { title: "用户中心", route: { name: "myprofile" } }
      ]
    };
  },
  // components注册组件 可以使用对应的标签来展示
  components: {
    myheader: myheader
  },
  created() {},
  mounted: function() {
      this.get_phone()
      this.get_avatar()
      this.get_token()
      // 注册拖拽容器
      let upload = document.querySelector('.upload');
      // 声明监听事件
      upload.addEventListener('dragenter', this.onDrag, false); // 按住
      upload.addEventListener('dragover', this.onDrag, false);  //拖拽悬停
      upload.addEventListener('drop', this.onDrop, false);  // 松开
  },
  methods: {
    //获取手机
    get_phone(){
      var uid = localStorage.getItem("uid");
      this.axios.get("http://127.0.0.1:8000/myapp/update_phone/", {
          params: {'uid': uid}
        }).then(result => {
          this.phone=result.data.phone
        })
    },
    update_phone(){
      // 判断手机号
        if(this.phone==""){ 
            this.phonemsg="手机号为空";
            return false;
        }else if (!/^1[365789]\d{9}$/.test(this.phone)){
              this.phonemsg="手机号格式不正确";
              return false;
        }
        let formdata = new FormData();
        formdata.append('uid',localStorage.getItem("uid"))
        formdata.append('phone',this.phone)
        this.axios.post("http://127.0.0.1:8000/myapp/update_phone/",formdata).then(res=>{
          console.log(res.data)
          if(res.data.code==200){
            this.$Message(res.data.msg)
            setTimeout("window.location.reload()",3);
          }
        })
    },
    //新建文件夹
    newdir(){
      var uid = localStorage.getItem("uid");
      this.axios.get("http://127.0.0.1:8000/myapp/upyun/", {
          params: { 'uid': uid,'dirname':this.dirname}
        }).then(result => {
          console.log(result.data)
          this.$$Message(result.data.msg)
        })
    },
    // 删除头像操作
    del_Avatar(){
      var uid = localStorage.getItem('uid')
      axios.delete('http://localhost:8000/myapp/upyun/',{
          params: { 'uid': uid }
        }).then(res=>{
          console.log(res.data)
          if(res.data.code==200){
            this.$Message(res.data.msg);
            setTimeout("window.location.reload()",3);
          }
        })
    },
    onDrag (e) {
      e.stopPropagation();
      e.preventDefault();
    },
    onDrop (e) {
      e.stopPropagation();
      e.preventDefault();
      //调用自定义上传方法
      this.upload_upyun(e.dataTransfer.files);
    },
    upload_upyun:function(files){
      // 获取参数
        let file = files[0];
        // let file = files.target.files[0];
      let param = new FormData();
      // 声明参数
      param.append('file',file)
      param.append("uid", localStorage.getItem("uid"));
      const config = {
				headers: { 'Content-Type': 'multipart/form-data' }
      } 
      var a = this
      // 上传图片
      axios.post('http://localhost:8000/myapp/upyun/', param, config).then(function(res) {
        if(res.status==200){
          a.$Message('修改成功');
          a.src='http://mdsave.test.upcdn.net/'+res.data.filename;
          setTimeout("window.location.reload()",3);
        }
      });
    },
    //画中画
    into:function(){
        var video =document.getElementById('video')
        if (video !== document.pictureInPictureElement) {
          // 尝试进入画中画模式
          video.requestPictureInPicture();    
          this.mymsg = '退出画中画';  
          } else {
          // 退出画中画
          document.exitPictureInPicture();
          this.mymsg = '进入画中画';
        }
    },
    // 请求token
    get_token(){
      this.axios.get("http://127.0.0.1:8000/myapp/qiniu/").then(result => {
          console.log(result.data.token)
          this.token = result.data.token
        });
    },
    // 存入七牛
    upload_qiniu:function(e){
  		//获取文件
  		let file = e.target.files[0];
  		//声明表单参数
  		let param = new FormData();
  		param.append('file',file,file.name);
  		param.append('token',this.token);
  		//自定义axios
  		const axios_qiniu = this.axios.create({withCredentials:false});
  		//发送请求
  		axios_qiniu({
  			method:'POST',
  			url:'http://up-z1.qiniup.com/',
  			data:param,
        timeout:30000,
        // 上传过程中的方法
        onUploadProgress:(e)=>{
          //计算上传百分比
          var complete = (e.loaded/e.total);
          // 处理美化
          if(complete < 1){
            this.load_percent=(complete*100).toFixed(2)+'%';

            this.load_int=parseInt((complete*100).toFixed(2))
          }
        }
  		}).then(result =>{
        console.log(result);
        if(result.status==200){
          //手动复制100%
          this.load_percent = '100%';
          this.load_int = 100;
          // this.src = "http://q9ksotoly.bkt.clouddn.com/"+result.data.key;
          this.videosrc = config['baseurl']+result.data.key;

        }

  		});
  	},
    upload(e) {
      // 获取文件
      let file = e.target.files[0];
      // 生名表单参数
      let formdata = new FormData();
      var uid = localStorage.getItem("uid");
      formdata.append("file", file, file.name);
      formdata.append("uid", uid);
      // 请求头
      let config = { headers: { "Content-Type": "multipart/form-data" } };

      // 请求后台
      this.axios
        .post("http://127.0.0.1:8000/myapp/upload/", formdata, config)
        .then(result => {
          console.log(result.data);
          if (result.data.code == 200) {
            this.src ="http://127.0.0.1:8000/static/upload/" + result.data.filename;
            this.$Message(result.data.msg);
          } else {
            this.$Message(result.data.msg);
          }
        });
    },
    get_avatar() {
      var uid = localStorage.getItem("uid");
      var myjwt = localStorage.getItem("jwt");
      this.axios.get("http://127.0.0.1:8000/myapp/upload/", {
          params: { 'uid': uid,'jwt':myjwt}
        }).then(result => {
          if(result.data.filename=='user.png'){
            this.src ="http://127.0.0.1:8000/static/upload/" + result.data.filename;
          }else{
            this.src ="http://mdsave.test.upcdn.net/" + result.data.filename;
          }
          
        });
    }
  }
};
</script>
 
<style>
.td {
  padding: 10px;
}
table {
  margin: 0 auto;
}
.code {
  cursor: pointer;
}
.upload {
  margin: 100px auto;
  width: 300px;
  height: 150px;
  border: 2px dashed #f00;
  padding-top: 50px;
  padding-left: 80px;
}
</style>